﻿@using Project.Constraints.Models.Request
@using System.Collections
@using System.Data
@using Project.Constraints.UI.Extensions
@typeparam TRowData
@typeparam TQuery where TQuery : IRequest, new()
<Card>
    <Table DataSource="Datas"
           Loading="@Options.Loading"
           Bordered="@true"
           Resizable="@true"
           DefaultExpandAllRows="@true"
           Size="@TableSize.Small"
           ScrollX="@Options.ScrollX"
           Total="@Total"
           @bind-PageIndex="@Options.Query.PageIndex"
           @bind-PageSize="@Options.Query.PageSize"
           HidePagination="!Options.Pager">
        <ChildContent>
            @foreach (var item in Options.Columns)
            {
                @BuildColumn(item)   
            }
            @if (Options.Buttons?.Count > 0)
            {
                @foreach (var btnGroup in Options.Buttons.GroupBy(btn => btn.Group))
                {
                    <ActionColumn Title=@(TableLocalizer[btnGroup.Key]) Align="@ColumnAlign.Center" Fixed="ColumnFixPlacement.Right" Width="@Options.ActionColumnWidth">
                        @{
                            var btns = btnGroup.Where(b => b.CheckVisible(context)).ToList();
                            if (Options.ActionButtonColumn.HasValue)
                            {
                                <Project.Web.Shared.ComponentHelper.MGrid GridColumns="@Options.ActionButtonColumn.Value" Gap="5px">
                                    @foreach (var btn in btns)
                                    {
                                        @CreateButton(btn, context)
                                    }
                                </Project.Web.Shared.ComponentHelper.MGrid>
                            }
                            else if (btns.Count <= 2)
                            {
                                foreach (var btn in btns)
                                {
                                    @CreateButton(btn, context)
                                }
                            }
                            else
                            {
                                var first = btns[0];
                                @CreateButton(first, context)
                                <Dropdown>
                                    <Overlay>
                                        <Menu>
                                            @for (var i = 1; i < btns.Count; i++)
                                            {
                                                var btn = btns[i];
                                                <MenuItem>
                                                    @CreateButton(btn, context)
                                                </MenuItem>
                                            }
                                        </Menu>
                                    </Overlay>
                                    <ChildContent>
                                        <a @onclick:preventDefault>
                                            @TableLocalizer["TableTips.More"] <Icon Type="down" />
                                        </a>
                                    </ChildContent>
                                </Dropdown>
                            }
                        }
                    </ActionColumn>
                }
            }
        </ChildContent>
        <PaginationTemplate Context="pageContext">
            <Pagination Class="@pageContext.PaginationClass"
                        Total="@pageContext.Total"
                        PageSize="@pageContext.PageSize"
                        Current="@pageContext.PageIndex"
                        ShowTotal="TotalFragment"
                        ShowSizeChanger="@true"
                        ShowQuickJumper="@true"
                        OnChange="@PaginationChanged" />
        </PaginationTemplate>
    </Table>
</Card>

@code {
    [Parameter, NotNull] public TableOptions<TRowData, TQuery>? Options { get; set; }

    [Inject, NotNull] IStringLocalizer<TableOptions>? TableLocalizer { get; set; }
    [Inject, NotNull] ConfirmService? ConfirmSrv { get; set; }
    [Inject, NotNull] MessageService? MessageSrv { get; set; }
    IEnumerable<TRowData> Datas => Options.Result?.Payload ?? Enumerable.Empty<TRowData>();
    int Total => Options.Result?.TotalRecord ?? 0;

    protected override void OnInitialized()
    {
        base.OnInitialized();
        Options.NotifyChanged = () => InvokeAsync(StateHasChanged);
    }

    private RenderFragment CreateButton(TableButton<TRowData> definition, TRowData context)
    {
        return
    @<Button Type="@Utils.GetButtonType(definition.ButtonType)"
                 Size="@ButtonSize.Small"
                 Danger="@definition.Danger"
                 Icon="@definition.Icon"
                 OnClickStopPropagation
                 OnClick="@(() => InvokeButtonAction(definition, context))">
        @(definition.GetLabel(context) ?? TableLocalizer[definition.Label])
    </Button>
    ;
    }

    private async Task InvokeButtonAction(TableButton<TRowData> definition, TRowData data)
    {
        if (definition.Danger)
        {
            var confirmResult = await ConfirmSrv.Show(
    TableLocalizer[definition.ConfirmContent ?? "TableTips.DangerActionConfirmContent"].Value
    , TableLocalizer[definition.ConfirmTitle ?? "TableTips.DangerActionConfirmTitle"].Value);
            if (confirmResult == ConfirmResult.OK)
            {
                await CallButtonAction();
            }
        }
        else
        {
            await CallButtonAction();
        }

        return;

        async Task CallButtonAction()
        {
            var result = await definition.Callback.Invoke(data);
            if (result is null)
            {
                return;
            }
            Options.OnTableButtonClickAsync?.Invoke(definition, result);
            if (result.IsSuccess)
            {
                var msg = result.Message ?? TableLocalizer["TableTips.ActionSuccess"].Value;
                _ = MessageSrv.Success(msg);
                if (Options.AutoRefreshData)
                    await Options.RefreshAsync();
            }
            else
            {
                _ = MessageSrv.Error(result.Message ?? "Error");
            }
        }
    }


    /// <summary>
    /// table总数
    /// </summary>
    Func<PaginationTotalContext, string> TotalFragment => (context) => $"{TableLocalizer["TableTips.Total"]}：{context.Total}";

    async Task PaginationChanged(PaginationEventArgs e)
    {
        Options.Query.PageIndex = e.Page;
        Options.Query.PageSize = e.PageSize;
        await Options.RefreshAsync();
    }

    RenderFragment BuildColumn(ColumnInfo col)
    {
        return builder => builder.Component<PropertyColumn<DataRow, object>>()
              .SetComponent(c => c.Title, col.Label)
              .SetComponent(c => c.Align, ColumnAlign.Center)
              .SetComponent(c => c.Property, row => row[col.PropertyOrFieldName])
              .Build();
    }

    
}
